package com.zjl.Zookeeper.第04章_服务器动态上下线监听案例;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
import org.junit.Test;

import java.io.IOException;
import java.util.List;

public class A_ {
    static ZooKeeper zooKeeper;
    static {
        // ZooKeeper服务器地址和端口  connectString的值不能有空格
        //String connectString = "82.157.71.243:2181,82.157.71.243:2181,82.157.71.243:2181";
        String connectString = "82.157.71.243:2181"; // ZooKeeper服务器地址和端口
        int sessionTimeout = 2000; // 会话超时时间（毫秒）
        try {
            zooKeeper = new ZooKeeper(connectString, sessionTimeout,
                    event -> {
                        // 这里可以处理WatchedEvent  如果在操作ZooKeeper时，设置了监听，则改动时会执行
                        System.out.println("getPath: " + event.getPath());//变化的路径
                        System.out.println("getState: " + event.getState().getIntValue());
                        System.out.println("getType: " + event.getType());
                        System.out.println("getWrapper: " + event.getWrapper());
                        System.out.println("event: " + event);
                        //第一个参数:节点路径   第二参数:是否开启监听 开启监听会使 连接zk处进行执行
                        List<String> children = null;
                        try {
                            children = zooKeeper.getChildren("/", true);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        System.out.println(children);

                    }
            );
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Test//查询节点下的节点信息  监听
    public void ls_true() throws Exception {
        //第一个参数:节点路径   第二参数:是否开启监听 开启监听会使 连接zk处进行执行
        List<String> children = zooKeeper.getChildren("/", true);
        System.out.println(children);

        Thread.sleep(100000);
    }
}
